﻿using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;
using UbiGamesBackupTool;
using System.Windows.Markup;
using static WpfTest.Win32;
using System.Diagnostics;

namespace WpfTest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);

        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        public static string ConfigFilePath = System.AppDomain.CurrentDomain.BaseDirectory + System.IO.Path.DirectorySeparatorChar+ "config.json";
        public static string FilePath = System.AppDomain.CurrentDomain.BaseDirectory + System.IO.Path.DirectorySeparatorChar + "config.json";

        public static string USERINFOLOCATION = System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\AppData\\Local\\Ubisoft Game Launcher\\users.dat";
        public string USERSETTINGLOCATION = System.Environment.GetEnvironmentVariable("USERPROFILE") + "\\AppData\\Local\\Ubisoft Game Launcher\\settings.yml";
        public static string UPLAYINSTALLLOCATION = GetUplayPath().Split(new char[] { '"', })[1].Substring(0, GetUplayPath().LastIndexOf('\\'));
        public static string UPLAYSAVEGAME = UPLAYINSTALLLOCATION + "\\savegames";
        public static string USERICONLOCATION = UPLAYINSTALLLOCATION + "\\cache\\avatars";
        public static string GAMELOGOCACHE = UPLAYINSTALLLOCATION + "\\cache\\assets";

        const char DirChar = '-';

        static private List<Game> SupportGameList { get; set; } = GetSupportGame();
        private UserInfo SelectUser { get; set; } = null;

        WindowInteropHelper wih = null;

        ImageBrush GameBtnDefaultImageBrush = null;
        SolidColorBrush GamePanelColorBrush = null;
        SolidColorBrush GamePanelSelectedColorBrush = null;
        ImageBrush UserImgDefaultImageBrush = null;
        private enum ToolMode
        {
            Backup, Restore
        }
        ToolMode toolMode = ToolMode.Backup;

        List<string> SelectGameList = new List<string>();
        private Config Toolconfig = null;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        //[StructLayout(LayoutKind.Sequential)]
        //public struct RECT
        //{
        //    public int Left;                             //最左坐标
        //    public int Top;                             //最上坐标
        //    public int Right;                           //最右坐标
        //    public int Bottom;                        //最下坐标
        //}
        GameStatusListener gameStatusListener;//游戏监听器

        NotifyIcon notifyIcon;
        public MainWindow()
        {
            InitializeComponent();
            wih = new WindowInteropHelper(this);//获取当前窗体句柄
            GameBtnDefaultImageBrush = (ImageBrush)FindResource("GameBtnDefaultImageBrush");            //寻找资源
            GamePanelColorBrush = (SolidColorBrush)FindResource("GamePanelColorBrush");                 //
            GamePanelSelectedColorBrush = (SolidColorBrush)FindResource("GamePanelSelectedColorBrush"); //
            UserImgDefaultImageBrush = (ImageBrush)FindResource("UserImgDefaultImageBrush");
            //GetNowLoginUserID();
            //Console.WriteLine(ConfigFilePath);

            if (File.Exists(ConfigFilePath))
            {
                using (Stream stream = new FileStream(ConfigFilePath, FileMode.Open))
                {
                    using (StreamReader reader = new StreamReader(stream)) {
                        Toolconfig = JsonConvert.DeserializeObject<Config>(reader.ReadToEnd());
                    }
                    if (Toolconfig==null) {
                        Toolconfig = new Config();
                        Toolconfig.Save();
                    }
                }
            }
            else {
                Toolconfig = new Config();
                Toolconfig.Save();
            }
        }

        private void GameExitListener(object sender, GameEventArgs gameEventArgs)
        {
            //游戏退出
            foreach (Game g in gameEventArgs.game)
            {
                Console.WriteLine("游戏   " + g.name + "   已退出...");
            }
            Action<string,List<Game>> action = new Action<string, List<Game>>(ShowExitGameTip);
            this.Dispatcher.BeginInvoke(action, gameEventArgs.game[0].Title,gameEventArgs.game);
        }

        private void GameActionListener(object sender, GameEventArgs gameEventArgs)
        {
            //游戏启动
            foreach (Game g in gameEventArgs.game) {
                Console.WriteLine("游戏   " + g.name + "   已启动...");
            }
            Action<string> action = new Action<string>(ShowRunGameTip);
            this.Dispatcher.BeginInvoke(action, gameEventArgs.game[0].Title);
        }
        public void ShowRunGameTip(string content) {
            //RECT rect = new RECT();
            //Console.WriteLine(hswd);
            //Console.WriteLine(rect.Left+"   "+rect.Top);
            //GetWindowRect(hswd,out rect);
            //Console.WriteLine(rect.Left + "   " + rect.Top);
            //new RunGameTipForm() { Top = rect.Top,Left = rect.Left }.Show();
            int tipShowMilliseconds = 1000;
            string tipTitle = content + "已启动";
            string tipContent;
            ToolTipIcon tipType;
            if (GetNowLoginUserID() == null)
            {
                tipContent = "准备失败，检查是否勾选“记住我”";
                tipType = ToolTipIcon.Warning;
            }
            else {
                tipContent = "备份已准备";
                tipType = ToolTipIcon.Info;
            }
            if (Toolconfig.RunGameTipStatus) {
                notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
            }
        }
        public void ShowExitGameTip(string content,List<Game> gamelist) {
            int tipShowMilliseconds = 1000;
            string tipTitle = content + "已结束";
            string tipContent;
            ToolTipIcon tipType;
            string UID = GetNowLoginUserID();
            if (UID == null)
            {
                tipContent = "尝试失败，检查是否勾选“记住我”";
                tipType = ToolTipIcon.Warning;
            }
            else
            {
                try
                {
                    String backupPath = Toolconfig.AllowBackupPath + System.IO.Path.DirectorySeparatorChar + SelectUser.UNAME;
                    if (!Directory.Exists(backupPath))
                    {
                        Directory.CreateDirectory(backupPath);
                    }
                    foreach (Game g in gamelist)
                    {
                        if (Directory.Exists(UPLAYSAVEGAME + System.IO.Path.DirectorySeparatorChar + UID + System.IO.Path.DirectorySeparatorChar + g.id)) {
                            CopyDirectory(UPLAYSAVEGAME + System.IO.Path.DirectorySeparatorChar + UID + System.IO.Path.DirectorySeparatorChar + g.id, backupPath);
                        }
                    }
                    OutBackupInfo(backupPath, new UserInfo { UID = UID, UNAME = GetUserNameforUID(UID),BackupTime = string.Format("{0:yyyy-MM-dd HH.mm.ss}", DateTime.Now),USERSAVEGAME = backupPath });
                    tipContent = "备份完成";
                    tipType = ToolTipIcon.Info;
                }
                catch (Exception e)
                {
                    tipContent = "备份失败";
                    tipType = ToolTipIcon.Error;
                    System.Windows.Forms.MessageBox.Show(e.ToString());
                }
            }
            if (Toolconfig.ExitGameTipStatus) {
                notifyIcon.ShowBalloonTip(tipShowMilliseconds, tipTitle, tipContent, tipType);
            }
        }
        /// <summary>
        /// 获取Uplay路径
        /// </summary>
        /// <returns>Uplay路径或是错误提示</returns>
        private static string GetUplayPath()
        {
            try
            {
                string strKeyName = string.Empty;
                string softPath = @"SOFTWARE\Classes\uplay\Shell\Open\Command";
                RegistryKey regKey = Registry.LocalMachine;
                RegistryKey regSubKey = regKey.OpenSubKey(softPath, false);

                object objResult = regSubKey.GetValue(strKeyName);
                RegistryValueKind regValueKind = regSubKey.GetValueKind(strKeyName);
                if (regValueKind == Microsoft.Win32.RegistryValueKind.String)
                {
                    return objResult.ToString();
                }
            }
            catch
            {
                return "自动获取Uplay安装路径失败,请尝试手动选择";
            }
            return null;
        }

        /// <summary>
        /// 获取支持的游戏列表
        /// </summary>
        /// <returns></returns>
        public static List<Game> GetSupportGame()
        {
            List<Game> gamelist = JsonConvert.DeserializeObject<List<Game>>(UbiGamesBackupTool.Properties.Resources.game);
            //try {
            //    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("UbiGamesBackupTool.Newtonsoft.Json.dll"))
            //    {
            //        using (StreamReader steamreader = new StreamReader(stream))
            //        {
            //            List<Game> gamelist1 = JsonConvert.DeserializeObject<List<Game>>(steamreader.ReadToEnd());
            //        }
            //    }
            //}
            //catch (Exception e) {
            //    System.Windows.Forms.MessageBox.Show("获取支持的游戏出错!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
            return gamelist;
        }

        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns>返回所有用户的集合</returns>
        public static List<UserInfo> GetBackupAllUserInfo()
        {
            List<UserInfo> UserList = new List<UserInfo>();
            try
            {
                using (Stream stream = new FileStream(USERINFOLOCATION, FileMode.Open, FileAccess.Read))
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        string content = reader.ReadToEnd();
                        int UserCount = 0;
                        int pos = 0;
                        while ((pos = content.IndexOf('�', pos + 1)) != -1)
                        {
                            UserCount++;
                            UserInfo user = new UserInfo();
                            int uidstart = content.IndexOf('$', pos) + 1;
                            int uidend = content.IndexOf('*', uidstart);
                            string uid = content.Substring(uidstart, uidend - uidstart);
                            //int unamestart = content.IndexOf('', uidend)+1;
                            int unamestart = content.IndexOf("=2", uidend) + 3;
                            int unameend = content.IndexOf(':', unamestart);
                            string username = content.Substring(unamestart, unameend - unamestart);
                            user.UID = uid;
                            user.UNAME = username;
                            user.USERSAVEGAME = UPLAYSAVEGAME + System.IO.Path.DirectorySeparatorChar + uid;
                            UserList.Add(user);
                        }

                    }
                }
            }
            catch (Exception e)
            {
                e.ToString();
            }
            return UserList;
        }

        /// <summary>
        /// 获取需要还原存档的用户列表
        /// </summary>
        /// <param name="path">备份路径</param>
        /// <returns>用户列表</returns>
        public static List<UserInfo> GetReStoreUserList(string path)
        {
            List<UserInfo> UserList = new List<UserInfo>();
            string[] userpath = Directory.GetDirectories(path);
            foreach (string dir in userpath)
            {
                string userjson = dir + System.IO.Path.DirectorySeparatorChar + "userinfo.json";
                if (File.Exists(userjson))
                {
                    using (Stream stream = new FileStream(userjson, FileMode.Open))
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            UserInfo user = JsonConvert.DeserializeObject<UserInfo>(reader.ReadToEnd());
                            user.USERSAVEGAME = dir;
                            UserList.Add(user);
                        }
                    }
                }
                else
                {
                    continue;
                }
            }
            return UserList;
        }

        public void InitUserList(String path)
        {
            List<UserInfo> userlist = null;
            SelectGameList = new List<string>();
            switch (toolMode)
            {
                case ToolMode.Backup:
                    userlist = GetBackupAllUserInfo();
                    break;
                case ToolMode.Restore:
                    userlist = GetReStoreUserList(path);
                    break;
            }
            foreach (UserInfo userinfo in userlist)
            {
                //-----------------------------开始添加用户---------------------------

                System.Windows.Controls.Button button = new System.Windows.Controls.Button();
                //button.Margin = new Padding(0, 0, 0, 0);
                UserListView.Children.Add(button);
                string imgpath = USERICONLOCATION + "\\" + userinfo.UID + "_64.png";
                ImageBrush brush = UserImgDefaultImageBrush;
                if (File.Exists(imgpath))
                {
                    ImageSource bi = ChangeBitmapToImageSource(OverDrawHeadImg(imgpath));
                    brush = new ImageBrush
                    {
                        ImageSource = bi
                    };
                }
                button.Background = brush;
                button.Width = 48;
                button.Height = 48;
                //button.BackgroundImageLayout = ImageLayout.Zoom;
                //button.FlatStyle = FlatStyle.Flat;
                //button.FlatAppearance.BorderSize = 0;
                button.Tag = userinfo;
                button.ToolTip = userinfo.UNAME;
                button.Click += new RoutedEventHandler(this.UserButtonClick);
                //toolTip1.SetToolTip(button, userinfo.UNAME);
                //CheckGameSaveDirectory();
            }
            SelectUser = userlist[0];
            InitGameListPanel();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            notifyIcon = new NotifyIcon();
            notifyIcon.Icon = UbiGamesBackupTool.Properties.Resources.UbiGameBackupToolICO;
            this.notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(this.NotifyIcon_MouseClick);
            notifyIcon.Visible = true;


            InitUserList(UPLAYSAVEGAME);
            gameStatusListener = new GameStatusListener();
            gameStatusListener.Process_Event += new GameStatusListener.Event_Handler(this.GameActionListener);
            gameStatusListener.Process_Exit += new GameStatusListener.Event_Handler(this.GameExitListener);
            if (Toolconfig.AllowBackup)
            {
                gameStatusListener.start();
            }
        }

        private void NotifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            Console.WriteLine("点击");
            //this.WindowState = WindowState.Normal;
            this.Visibility = Visibility.Visible;
            //this.Activate();
        }

        /// <summary>
        /// 切换用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserButtonClick(object sender, EventArgs e)
        {
            SelectUser = (UserInfo)((System.Windows.Controls.Button)sender).Tag;
            SelectGameList = new List<string>();
            //flowLayoutPanel2.Controls.Clear();
            //tableLayoutPanel1.Controls.Clear();
            if (toolMode == ToolMode.Restore)
            {
                toolstatus.Content = "由 " + SelectUser.UNAME + " 备份于" + SelectUser.BackupTime;
            }
            GameListView.Children.Clear();
            InitGameListPanel();
            GC.Collect();
        }
        /// <summary>
        /// 重绘头像为圆形
        /// </summary>
        /// <param name="file">图片路径</param>
        /// <returns>圆形头像</returns>
        private Bitmap OverDrawHeadImg(string file)
        {
            using (System.Drawing.Image i = new Bitmap(file))
            {
                Bitmap b = new Bitmap(i.Width, i.Height);
                using (Graphics g = Graphics.FromImage(b))
                {
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    using (GraphicsPath p = new GraphicsPath(FillMode.Alternate))
                    {
                        p.AddEllipse(0, 0, i.Width, i.Height);
                        g.FillPath(new TextureBrush(i), p);
                    }
                }
                return b;
            }
        }
        /// <summary>
        /// 检查并获取已存在的存档的游戏
        /// </summary>
        /// <returns>检测到的已存在存档的游戏列表</returns>
        public List<Game> CheckGameSaveDirectory()
        {
            List<Game> gamelist = SupportGameList;
            List<Game> Ugamelist = new List<Game>();
            if (SelectUser != null)
            {
                foreach (string str in GetGameSaveDirectory())
                {
                    foreach (Game g in gamelist)
                    {
                        if (g.id.Equals(str))
                        {
                            Ugamelist.Add(g);
                            break;
                        }
                    }
                }
            }
            return Ugamelist;
        }
        /// <summary>
        /// 获取用户所有存档文件夹
        /// </summary>
        /// <param name="uid">用户UID</param>
        /// <returns>返回存档文件夹名称，不包括路径</returns>
        public String[] GetGameSaveDirectory()
        {
            if (Directory.Exists(SelectUser.USERSAVEGAME))
            {
                String[] SaveDirectorys = Directory.GetDirectories(SelectUser.USERSAVEGAME);
                for (int i = 0; i < SaveDirectorys.Length; i++)
                {
                    SaveDirectorys[i] = SaveDirectorys[i].Substring(SaveDirectorys[i].LastIndexOf('\\') + 1, SaveDirectorys[i].Length - SaveDirectorys[i].LastIndexOf('\\') - 1);
                }
                return SaveDirectorys;
            }
            return new string[0];
        }
        /// <summary>
        /// 初始化游戏列表
        /// </summary>
        public void InitGameListPanel()
        {
            GameListView.Children.Clear();
            List<Game> Ugamelist = CheckGameSaveDirectory();
            foreach (Game g in Ugamelist)
            {
                //----------------------开始添加一个游戏在列表中---------------------
                WrapPanel panel = new WrapPanel
                {
                    Width = 330,
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                    Margin = new Thickness(4, 4, 4, 4),
                    Background = GamePanelColorBrush
                };

                System.Windows.Controls.Button pictureBox = new System.Windows.Controls.Button
                {
                    Width = 330,
                    Height = 181
                };
                System.Windows.Controls.Label label = new System.Windows.Controls.Label { Width = 330 };
                panel.Children.Add(pictureBox);
                panel.Children.Add(label);
                GameListView.Children.Add(panel);

                ImageBrush imageBrush = new ImageBrush();
                if (File.Exists(GAMELOGOCACHE + "\\" + g.img))
                {
                    imageBrush.ImageSource = new BitmapImage(new Uri(MainWindow.GAMELOGOCACHE + "\\" + g.img));
                    pictureBox.Background = imageBrush;
                }
                else
                {
                    pictureBox.Background = GameBtnDefaultImageBrush;
                }

                pictureBox.Click += new RoutedEventHandler(this.GamePanelClicked);
                pictureBox.Tag = g.id;

                label.Content = g.name+"-"+g.Version;
                label.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;

            }
            GC.Collect();
        }

        /// <summary>
        /// 游戏列表中 pictureBox的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GamePanelClicked(object sender, EventArgs e)
        {
            System.Windows.Controls.Button pictureBox = (System.Windows.Controls.Button)sender;
            WrapPanel wrapPanel = (WrapPanel)pictureBox.Parent;
            string gid = pictureBox.Tag.ToString();
            if (SelectGameList.Contains(gid))
            {
                SelectGameList.Remove(gid);
                wrapPanel.Background = GamePanelColorBrush;
            }
            else
            {
                SelectGameList.Add(gid);
                wrapPanel.Background = GamePanelSelectedColorBrush;
            }

        }

        private void CloseBtn_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
        }
        /// <summary>
        /// 切换备份或还原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChangeModeBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.toolMode == ToolMode.Backup)
            {
                FolderBrowserDialog folderBrowserDialogBackupTo = new FolderBrowserDialog();
                if (Toolconfig.AllowBackup) {
                    folderBrowserDialogBackupTo.SelectedPath = Toolconfig.AllowBackupPath;
                }
                System.Windows.MessageBox.Show("请选择备份的位置以开始还原");
                if (folderBrowserDialogBackupTo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    //button3.Visible = false;
                    //button5.Visible = true;
                    toolMode = ToolMode.Restore;
                    UserListView.Children.Clear();
                    try
                    {
                        InitUserList(folderBrowserDialogBackupTo.SelectedPath);
                        InitGameListPanel();
                        toolstatus.Content = "由 " + SelectUser.UNAME + " 备份于" + SelectUser.BackupTime;
                        BackReBtn.Background = (ImageBrush)FindResource("RestoreImageBrush");
                        BackReBtn.ToolTip = "还原";
                    }
                    catch (Exception)
                    {

                        toolMode = ToolMode.Backup;
                        //button3.Visible = true;
                        //button5.Visible = false;
                        //throw;
                        InitUserList(UPLAYSAVEGAME);
                        InitGameListPanel();
                        toolstatus.Content = "选择将要备份的游戏存档";
                        BackReBtn.Background = (ImageBrush)FindResource("BackupImageBrush");
                        System.Windows.MessageBox.Show("这个路径里并没有备份好的存档！回到备份模式");
                        BackReBtn.ToolTip = "备份";
                    }

                }
                folderBrowserDialogBackupTo.Dispose();
            }
            else
            {
                //button3.Visible = true;
                //button5.Visible = false;
                toolMode = ToolMode.Backup;

                UserListView.Children.Clear();

                InitUserList(UPLAYSAVEGAME);
                InitGameListPanel();
                toolstatus.Content = "选择将要备份的游戏存档";
                BackReBtn.Background = (ImageBrush)FindResource("BackupImageBrush");
                BackReBtn.ToolTip = "备份";
            }
        }

        private void BackReBtn_Click(object sender, RoutedEventArgs e)
        {
            if (toolMode == ToolMode.Restore)
            {
                if (SelectGameList.Count > 0)
                {
                    if (MessageBoxResult.OK == System.Windows.MessageBox.Show("确定要还原这些游戏？", "确定", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                    {
                        String ReStorePath = UPLAYSAVEGAME + System.IO.Path.DirectorySeparatorChar + SelectUser.UID;

                        foreach (string GID in SelectGameList)
                        {
                            CopyDirectory(SelectUser.USERSAVEGAME + System.IO.Path.DirectorySeparatorChar + GID, ReStorePath);
                        }
                        System.Windows.MessageBox.Show("还原完成！");
                        GC.Collect();
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("还未选择存档！");
                }
            }
            else
            {
                if (SelectGameList.Count > 0)
                {
                    if (MessageBoxResult.OK == System.Windows.MessageBox.Show("确定要备份这些游戏？", "确定", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                    {
                        FolderBrowserDialog folderBrowserDialogBackupTo = new FolderBrowserDialog();
                        if (folderBrowserDialogBackupTo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            SelectUser.BackupTime = string.Format("{0:yyyy-MM-dd HH.mm.ss}", DateTime.Now);
                            String backupPath = folderBrowserDialogBackupTo.SelectedPath + System.IO.Path.DirectorySeparatorChar + SelectUser.UNAME + " " + SelectUser.BackupTime;

                            foreach (string path in SelectGameList)
                            {
                                CopyDirectory(UPLAYSAVEGAME + System.IO.Path.DirectorySeparatorChar + SelectUser.UID + System.IO.Path.DirectorySeparatorChar + path, backupPath);
                            }
                            OutBackupInfo(backupPath);
                            System.Windows.MessageBox.Show("备份完成！");
                            GC.Collect();
                        }
                        folderBrowserDialogBackupTo.Dispose();
                    }

                }
                else
                {
                    System.Windows.MessageBox.Show("还未选择游戏！");
                }
            }
        }
        /// <summary>
        /// 复制存档目录
        /// </summary>
        /// <param name="srcdir">游戏存档源文件夹</param>
        /// <param name="desdir">目标存档文件夹</param>
        private void CopyDirectory(string srcdir, string desdir)
        {
            string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1);
            string desfolderdir = desdir + "\\" + folderName;
            if (desdir.LastIndexOf("\\") == (desdir.Length - 1))
            {
                desfolderdir = desdir + folderName;
            }
            string[] filenames = Directory.GetFileSystemEntries(srcdir);
            foreach (string file in filenames)// 遍历所有的文件和目录
            {
                if (Directory.Exists(file))// 先当作目录处理 如果存在这个目录就递归Copy该目录下面的文件
                {
                    string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    if (!Directory.Exists(currentdir))
                    {
                        Directory.CreateDirectory(currentdir);
                    }
                    CopyDirectory(file, desfolderdir);
                }
                else // 否则直接copy文件
                {
                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);
                    srcfileName = desfolderdir + "\\" + srcfileName;
                    if (!Directory.Exists(desfolderdir))
                    {
                        Directory.CreateDirectory(desfolderdir);
                    }
                    File.Copy(file, srcfileName, true);
                }
            }
        }
        /// <summary>
        /// 输出备份信息
        /// </summary>
        /// <param name="path">备份地址</param>
        public void OutBackupInfo(string path)
        {
            using (Stream stream = new FileStream(path + System.IO.Path.DirectorySeparatorChar + "userinfo.json", FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine(JsonConvert.SerializeObject(SelectUser));
                    writer.Flush();
                }
            }
        }
        /// <summary>
        /// 输出备份信息
        /// </summary>
        /// <param name="path">备份地址</param>
        /// <param name="userInfo">用户信息</param>
        public void OutBackupInfo(string path,UserInfo userInfo)
        {
            using (Stream stream = new FileStream(path + System.IO.Path.DirectorySeparatorChar + "userinfo.json", FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine(JsonConvert.SerializeObject(userInfo));
                    writer.Flush();
                }
            }
        }
        /// <summary>
        /// 从bitmap转换成ImageSource
        /// </summary>
        /// <param name="icon"></param>
        /// <returns></returns>
        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            //Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            if (!DeleteObject(hBitmap))
            {

            }
            return wpfBitmap;
        }

        private void Min_Click(object sender, RoutedEventArgs e)
        {
            //WindowState = WindowState.Minimized;
            this.Visibility = Visibility.Hidden;
        }

        //-----------------------------------窗体移动-----------------------------------------

        private void TitlePanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            SendMessage(wih.Handle, Win32.WM_NCLBUTTONDOWN, (int)Win32.HitTest.HTCAPTION, 0);
            return;
        }

        private void TitlePanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void TitlePanel_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {

        }
        //------------------------------------------------------------------------------------

        //-------------------------------------最大化-----------------------------------

        /// <summary>
        /// 设置窗体最大大小（不遮挡任务栏）
        /// </summary>
        /// <param name="frm"></param>
        public virtual void SetFormMax(Window window)
        {
            window.MaxWidth = Screen.PrimaryScreen.WorkingArea.Width;
            window.MaxHeight = Screen.PrimaryScreen.WorkingArea.Height;
        }

        //------------------------------------------------------------------------------------

        //-------------------------------窗体大小更改-----------------------------------------
        private void Window_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {

        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (WindowState == WindowState.Maximized)
            {
                MaxBtn.Background = (ImageBrush)FindResource("MaxImageBrush");
            }
            else if (WindowState == WindowState.Normal)
            {
                MaxBtn.Background = (ImageBrush)FindResource("NormalImageBrush");
            }
        }


        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
            if (hwndSource != null)
            {
                hwndSource.AddHook(new HwndSourceHook(this.WndProc));
            }
        }

        protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case Win32.WM_GETMINMAXINFO: // WM_GETMINMAXINFO message  
                    WmGetMinMaxInfo(hwnd, lParam);
                    handled = true;
                    break;
                case Win32.WM_NCHITTEST: // WM_NCHITTEST message  
                    return WmNCHitTest(lParam, ref handled);
            }
            return IntPtr.Zero;
        }
        private void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
        {
            // MINMAXINFO structure  
            Win32.MINMAXINFO mmi = (Win32.MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(Win32.MINMAXINFO));

            // Get handle for nearest monitor to this window  
            WindowInteropHelper wih = new WindowInteropHelper(this);
            IntPtr hMonitor = Win32.MonitorFromWindow(wih.Handle, Win32.MONITOR_DEFAULTTONEAREST);

            // Get monitor info  
            Win32.MONITORINFOEX monitorInfo = new Win32.MONITORINFOEX();
            monitorInfo.cbSize = Marshal.SizeOf(monitorInfo);
            Win32.GetMonitorInfo(new HandleRef(this, hMonitor), monitorInfo);

            // Get HwndSource  
            HwndSource source = HwndSource.FromHwnd(wih.Handle);
            if (source == null)
                // Should never be null  
                throw new Exception("Cannot get HwndSource instance.");
            if (source.CompositionTarget == null)
                // Should never be null  
                throw new Exception("Cannot get HwndTarget instance.");

            // Get transformation matrix  
            System.Windows.Media.Matrix matrix = source.CompositionTarget.TransformFromDevice;

            // Convert working area  
            Win32.RECT workingArea = monitorInfo.rcWork;
            System.Windows.Point dpiIndependentSize =
                matrix.Transform(new System.Windows.Point(
                        workingArea.Right - workingArea.Left,
                        workingArea.Bottom - workingArea.Top
                        ));

            // Convert minimum size  
            System.Windows.Point dpiIndenpendentTrackingSize = matrix.Transform(new System.Windows.Point(
                this.MinWidth,
                this.MinHeight
                ));

            // Set the maximized size of the window  
            mmi.ptMaxSize.x = (int)dpiIndependentSize.X;
            mmi.ptMaxSize.y = (int)dpiIndependentSize.Y;

            // Set the position of the maximized window  
            mmi.ptMaxPosition.x = 0;
            mmi.ptMaxPosition.y = 0;

            // Set the minimum tracking size  
            mmi.ptMinTrackSize.x = (int)dpiIndenpendentTrackingSize.X;
            mmi.ptMinTrackSize.y = (int)dpiIndenpendentTrackingSize.Y;

            Marshal.StructureToPtr(mmi, lParam, true);
        }
        private readonly int customBorderThickness = 7;
        private readonly int cornerWidth = 8;
        /// <summary>  
        /// Mouse point used by HitTest  
        /// </summary>  
        private System.Windows.Point mousePoint = new System.Windows.Point();
        private IntPtr WmNCHitTest(IntPtr lParam, ref bool handled)
        {
            // Update cursor point  
            // The low-order word specifies the x-coordinate of the cursor.  
            // #define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))  
            this.mousePoint.X = (int)(short)(lParam.ToInt32() & 0xFFFF);
            // The high-order word specifies the y-coordinate of the cursor.  
            // #define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))  
            this.mousePoint.Y = (int)(short)(lParam.ToInt32() >> 16);

            // Do hit test  
            handled = true;
            if (Math.Abs(this.mousePoint.Y - this.Top) <= this.cornerWidth
        && Math.Abs(this.mousePoint.X - this.Left) <= this.cornerWidth)
            { // Top-Left  
                return new IntPtr((int)Win32.HitTest.HTTOPLEFT);
            }
            else if (Math.Abs(this.ActualHeight + this.Top - this.mousePoint.Y) <= this.cornerWidth
                && Math.Abs(this.mousePoint.X - this.Left) <= this.cornerWidth)
            { // Bottom-Left  
                return new IntPtr((int)Win32.HitTest.HTBOTTOMLEFT);
            }
            else if (Math.Abs(this.mousePoint.Y - this.Top) <= this.cornerWidth
                && Math.Abs(this.ActualWidth + this.Left - this.mousePoint.X) <= this.cornerWidth)
            { // Top-Right  
                return new IntPtr((int)Win32.HitTest.HTTOPRIGHT);
            }
            else if (Math.Abs(this.ActualWidth + this.Left - this.mousePoint.X) <= this.cornerWidth
                && Math.Abs(this.ActualHeight + this.Top - this.mousePoint.Y) <= this.cornerWidth)
            { // Bottom-Right  
                return new IntPtr((int)Win32.HitTest.HTBOTTOMRIGHT);
            }
            else if (Math.Abs(this.mousePoint.X - this.Left) <= this.customBorderThickness)
            { // Left  
                return new IntPtr((int)Win32.HitTest.HTLEFT);
            }
            else if (Math.Abs(this.ActualWidth + this.Left - this.mousePoint.X) <= this.customBorderThickness)
            { // Right  
                return new IntPtr((int)Win32.HitTest.HTRIGHT);
            }
            else if (Math.Abs(this.mousePoint.Y - this.Top) <= this.customBorderThickness)
            { // Top  
                return new IntPtr((int)Win32.HitTest.HTTOP);
            }
            else if (Math.Abs(this.ActualHeight + this.Top - this.mousePoint.Y) <= this.customBorderThickness)
            { // Bottom  
                return new IntPtr((int)Win32.HitTest.HTBOTTOM);
            }
            else
            {
                handled = false;
                return IntPtr.Zero;
            }
        }
        //------------------------------------------------结束-------------------------------
        private void MaxBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
                this.WindowState = WindowState.Normal;
            else
                this.WindowState = WindowState.Maximized;
        }

        public string GetNowLoginUserID()
        {
            if (File.Exists(USERSETTINGLOCATION))
            {
                using (Stream stream = new FileStream(USERSETTINGLOCATION, FileMode.Open))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string temp;
                        while ((temp = reader.ReadLine()) != null)
                        {
                            if (temp == "user:")
                            {
                                while ((temp = reader.ReadLine()) != null)
                                {
                                    if (temp.Contains("password:"))
                                    {
                                        string usertemp = temp.Substring(temp.IndexOf("password:") + 9).Trim().Trim('"');
                                        if (usertemp != "")
                                        {
                                            using (Stream userstream = new FileStream(USERINFOLOCATION, FileMode.Open))
                                            {
                                                using (StreamReader userreader = new StreamReader(userstream))
                                                {
                                                    string[] userinfos = userreader.ReadToEnd().Split('$');
                                                    foreach (string userinfo in userinfos)
                                                    {
                                                        if (userinfo.Contains(usertemp))
                                                        {
                                                            //int uidstart = content.IndexOf('$', pos) + 1;
                                                            int uidend = userinfo.IndexOf('*');
                                                            string uid = userinfo.Substring(0, uidend);
                                                            return uid;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        return null;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }

        public string GetUserNameforUID(string UID) {
            if (File.Exists(USERINFOLOCATION)) {
                using (Stream userstream = new FileStream(USERINFOLOCATION, FileMode.Open))
                {
                    using (StreamReader userreader = new StreamReader(userstream))
                    {
                        string[] userinfos = userreader.ReadToEnd().Split('$');
                        foreach (string userinfo in userinfos)
                        {
                            if (userinfo.Contains(UID))
                            {
                                int uidend = userinfo.IndexOf('*');
                                int unamestart = userinfo.IndexOf("=2",uidend) + 3;
                                int unameend = userinfo.IndexOf(':', unamestart);
                                return userinfo.Substring(unamestart, unameend - unamestart);
                            }
                        }
                    }
                }
            }
            return null;
        }

        private void AllowBackup_Click(object sender, RoutedEventArgs e)
        {
            zSetting.Children.Clear();
            WrapPanel rootElement;
            Assembly asmbly = Assembly.GetExecutingAssembly();

            using (Stream stream = asmbly.GetManifestResourceStream("UbiGamesBackupTool.AllowBackup.xaml"))
            {
                rootElement = (WrapPanel)XamlReader.Load(stream);
                if (!Toolconfig.AllowBackup)
                {
                    System.Windows.Controls.CheckBox checkBox =  rootElement.FindName("AllowBackupCkb") as System.Windows.Controls.CheckBox;
                    checkBox.Click += new RoutedEventHandler(AllowBackupSettingCheckBox_OnChecked);
                    checkBox.IsChecked = false;
                    System.Windows.Controls.Button button = rootElement.FindName("AllowBackupPathChooseBtn") as System.Windows.Controls.Button;
                    button.Click += new RoutedEventHandler(AllowBackupChoosePathBtn_OnClicked);
                    System.Windows.Controls.TextBox textBox = rootElement.FindName("AllowBackupPathTextBox") as System.Windows.Controls.TextBox;
                    textBox.Text = Toolconfig.AllowBackupPath;
                    textBox.TextChanged += new TextChangedEventHandler(AllowBackupPathTextBox_TextChanged);
                    textBox.IsEnabled = false;
                    button.IsEnabled = false;
                    System.Windows.Controls.Button button1 = rootElement.FindName("AddListenerGameBtn") as System.Windows.Controls.Button;
                    button1.Click += new RoutedEventHandler(AddListenerGameBtn_OnClicked);
                    button1.IsEnabled = false;
                    WrapPanel wrapPanel = rootElement.FindName("ListenerPosSettingPanel") as WrapPanel;
                    wrapPanel.IsEnabled = false;
                }
                else {
                    System.Windows.Controls.CheckBox checkBox = rootElement.FindName("AllowBackupCkb") as System.Windows.Controls.CheckBox;
                    checkBox.Click += new RoutedEventHandler(AllowBackupSettingCheckBox_OnChecked);
                    checkBox.IsChecked = true;
                    System.Windows.Controls.Button button = rootElement.FindName("AllowBackupPathChooseBtn") as System.Windows.Controls.Button;
                    button.Click += new RoutedEventHandler(AllowBackupChoosePathBtn_OnClicked);
                    System.Windows.Controls.TextBox textBox = rootElement.FindName("AllowBackupPathTextBox") as System.Windows.Controls.TextBox;
                    textBox.Text = Toolconfig.AllowBackupPath;
                    textBox.TextChanged += new TextChangedEventHandler(AllowBackupPathTextBox_TextChanged);
                    System.Windows.Controls.Button button1 = rootElement.FindName("AddListenerGameBtn") as System.Windows.Controls.Button;
                    button1.Click += new RoutedEventHandler(AddListenerGameBtn_OnClicked);
                    WrapPanel wrapPanel = rootElement.FindName("ListenerPosSettingPanel") as WrapPanel;
                }
                Console.WriteLine("注册事件");
                System.Windows.Controls.RadioButton radioButton1 = rootElement.FindName("radiobtn1") as System.Windows.Controls.RadioButton;
                System.Windows.Controls.RadioButton radioButton2 = rootElement.FindName("radiobtn2") as System.Windows.Controls.RadioButton;
                System.Windows.Controls.RadioButton radioButton3 = rootElement.FindName("radiobtn3") as System.Windows.Controls.RadioButton;
                System.Windows.Controls.RadioButton radioButton4 = rootElement.FindName("radiobtn4") as System.Windows.Controls.RadioButton;
                switch (Toolconfig.AllowBackupShowLocation)
                {
                    case "TopLeft":
                        radioButton1.IsChecked = true;
                        break;
                    case "TopRight":
                        radioButton2.IsChecked = true;
                        break;
                    case "BottomLeft":
                        radioButton3.IsChecked = true;
                        break;
                    case "BottomRight":
                        radioButton4.IsChecked = true;
                        break;
                }
                radioButton1.Checked += new RoutedEventHandler(RadioButton_Clicked);
                radioButton2.Checked += new RoutedEventHandler(RadioButton_Clicked);
                radioButton3.Checked += new RoutedEventHandler(RadioButton_Clicked);
                radioButton4.Checked += new RoutedEventHandler(RadioButton_Clicked);

                System.Windows.Controls.CheckBox checkBox1 = rootElement.FindName("RunGameTipStatusCkb") as System.Windows.Controls.CheckBox;
                System.Windows.Controls.CheckBox checkBox2 = rootElement.FindName("ExitGameTipStatusCkb") as System.Windows.Controls.CheckBox;
                checkBox1.IsChecked = Toolconfig.RunGameTipStatus;
                checkBox1.Click += new RoutedEventHandler(RunGameTipStatusCkb_Checked);
                checkBox2.IsChecked = Toolconfig.ExitGameTipStatus;
                checkBox2.Click += new RoutedEventHandler(ExitGameTipStatusCkb_Checked);
                zSetting.Children.Add(rootElement);
            }
        }

        private void ExitGameTipStatusCkb_Checked(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
            if (checkBox.IsChecked == true)
            {
                Toolconfig.ExitGameTipStatus = true;
            }
            else {
                Toolconfig.ExitGameTipStatus = false;
            }
            Toolconfig.Save();
        }
        private void RunGameTipStatusCkb_Checked(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
            if (checkBox.IsChecked == true)
            {
                Toolconfig.RunGameTipStatus = true;
            }
            else
            {
                Toolconfig.RunGameTipStatus = false;
            }
            Toolconfig.Save();
        }

        private void AllowBackupPathTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            System.Windows.Controls.TextBox textbox = (System.Windows.Controls.TextBox)sender;
            if (Directory.Exists(textbox.Text))
            {
                Toolconfig.AllowBackupPath = textbox.Text;
                Toolconfig.Save();
            }
            else {
                System.Windows.Forms.MessageBox.Show("文件夹不存在，请重新输入!","警告",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
        }

        private void AddListenerGameBtn_OnClicked(object sender, RoutedEventArgs e)
        {
            ChooseListenerGameWindow chooseListenerGameWindow = new ChooseListenerGameWindow
            {
                Owner = this
            };
            chooseListenerGameWindow.ShowDialog();
            GC.Collect();
            gameStatusListener.restart();
        }

        private void AllowBackupChoosePathBtn_OnClicked(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            FrameworkElement rootpanel = ((System.Windows.Controls.Button)sender).Parent as FrameworkElement;
            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                ((System.Windows.Controls.TextBox)rootpanel.FindName("AllowBackupPathTextBox")).Text = folderBrowserDialog.SelectedPath;
            }
            folderBrowserDialog.Dispose();
        }

        private void AllowBackupSettingCheckBox_OnChecked(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
            FrameworkElement rootPanel = checkBox.Parent as FrameworkElement;
            
            if (checkBox.IsChecked == true)
            {
                System.Windows.Controls.Button button = rootPanel.FindName("AllowBackupPathChooseBtn") as System.Windows.Controls.Button;
                System.Windows.Controls.TextBox textBox = rootPanel.FindName("AllowBackupPathTextBox") as System.Windows.Controls.TextBox;
                textBox.IsEnabled = true;
                button.IsEnabled = true;
                System.Windows.Controls.Button button1 = rootPanel.FindName("AddListenerGameBtn") as System.Windows.Controls.Button;
                button1.IsEnabled = true;
                WrapPanel wrapPanel = rootPanel.FindName("ListenerPosSettingPanel") as WrapPanel;
                wrapPanel.IsEnabled = true;

                System.Windows.Controls.CheckBox RunGameTipStatusCkb = rootPanel.FindName("RunGameTipStatusCkb") as System.Windows.Controls.CheckBox;
                System.Windows.Controls.CheckBox ExitGameTipStatusCkb = rootPanel.FindName("ExitGameTipStatusCkb") as System.Windows.Controls.CheckBox;
                RunGameTipStatusCkb.IsEnabled = true;
                ExitGameTipStatusCkb.IsEnabled = true;

                gameStatusListener.restart();
            }
            else {
                System.Windows.Controls.Button button = rootPanel.FindName("AllowBackupPathChooseBtn") as System.Windows.Controls.Button;
                System.Windows.Controls.TextBox textBox = rootPanel.FindName("AllowBackupPathTextBox") as System.Windows.Controls.TextBox;
                textBox.IsEnabled = false;
                button.IsEnabled = false;
                System.Windows.Controls.Button button1 = rootPanel.FindName("AddListenerGameBtn") as System.Windows.Controls.Button;
                button1.IsEnabled = false;
                WrapPanel wrapPanel = rootPanel.FindName("ListenerPosSettingPanel") as WrapPanel;
                wrapPanel.IsEnabled = false;

                System.Windows.Controls.CheckBox RunGameTipStatusCkb = rootPanel.FindName("RunGameTipStatusCkb") as System.Windows.Controls.CheckBox;
                System.Windows.Controls.CheckBox ExitGameTipStatusCkb = rootPanel.FindName("ExitGameTipStatusCkb") as System.Windows.Controls.CheckBox;
                RunGameTipStatusCkb.IsEnabled = false;
                ExitGameTipStatusCkb.IsEnabled = false;

                gameStatusListener.stop();
            }
            Toolconfig.AllowBackup = checkBox.IsChecked.Value;
            Toolconfig.Save();
        }

        private void RadioButton_Clicked(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.RadioButton radioButton = sender as System.Windows.Controls.RadioButton;
            switch (radioButton.Content.ToString()) {
                case "左上":
                    Console.WriteLine("左上");
                    Toolconfig.AllowBackupShowLocation = "TopLeft";
                    break;
                case "左下":
                    Console.WriteLine("左下");
                    Toolconfig.AllowBackupShowLocation = "BottomLeft";
                    break;
                case "右上":
                    Console.WriteLine("右上");
                    Toolconfig.AllowBackupShowLocation = "TopRight";
                    break;
                case "右下":
                    Console.WriteLine("右下");
                    Toolconfig.AllowBackupShowLocation = "BottomRight";
                    break;
            }
            Toolconfig.Save();
        }

        private void Settingokbtn_Click(object sender, RoutedEventArgs e)
        {
            zSetting.Children.Clear();
            Setting.Visibility = Visibility.Collapsed;
            Main.Visibility = Visibility.Visible;
        }

        private void SettingBtn_Click(object sender, RoutedEventArgs e)
        {
            Main.Visibility = Visibility.Collapsed;

            AllSetting_Click(null,null);
            Setting.Visibility = Visibility.Visible;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            notifyIcon.Visible = false;
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            zSetting.Children.Clear();
            DockPanel rootElement;
            Assembly asmbly = Assembly.GetExecutingAssembly();

            using (Stream stream = asmbly.GetManifestResourceStream("UbiGamesBackupTool.About.xaml"))
            {
                rootElement = (DockPanel)XamlReader.Load(stream);
                TextBlock textBlock = (TextBlock)rootElement.FindName("ToolVersion");
                textBlock.Text = "当前版本：" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                System.Windows.Controls.Button button = rootElement.FindName("Toolfeedback") as System.Windows.Controls.Button;
                button.Click += new RoutedEventHandler(AboutfeedbackBtn_Clicked);
            }
            zSetting.Children.Add(rootElement);
        }

        private void AboutfeedbackBtn_Clicked(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://jq.qq.com/?_wv=1027&k=50pui0f");
        }

        private void AllSetting_Click(object sender, RoutedEventArgs e)
        {
            zSetting.Children.Clear();
            WrapPanel rootElement;
            Assembly asmbly = Assembly.GetExecutingAssembly();

            using (Stream stream = asmbly.GetManifestResourceStream("UbiGamesBackupTool.AllSetting.xaml"))
            {
                rootElement = (WrapPanel)XamlReader.Load(stream);
                System.Windows.Controls.CheckBox checkBox = rootElement.FindName("powerCkb") as System.Windows.Controls.CheckBox;
                checkBox.Click += new RoutedEventHandler(powerCkb_Checked);

                System.Windows.Controls.Button ShortcutButton = rootElement.FindName("ShortcutButton") as System.Windows.Controls.Button;
                ShortcutButton.Click += new RoutedEventHandler(ShortcutButton_Clicked);

                RegistryKey RKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                string[] keynames = RKey.GetValueNames();
                foreach (string keyname in keynames) {
                    if (keyname == "UbiGamesBackupTool") {
                        checkBox.IsChecked = true;
                    }
                }
            }
            zSetting.Children.Add(rootElement);
        }

        private void ShortcutButton_Clicked(object sender, RoutedEventArgs e)
        {
            //Console.WriteLine(this.GetType().Assembly.Location);
            ShortcutCreator.CreateShortcutOnDesktop("UbiGamesBackupTool", this.GetType().Assembly.Location);
        }

        private void powerCkb_Checked(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.CheckBox checkBox = sender as System.Windows.Controls.CheckBox;
            if (checkBox.IsChecked == true)
            {
                try {
                    // 添加到 当前登陆用户的 注册表启动项
                    string startuppath = Process.GetCurrentProcess().MainModule.FileName;
                    RegistryKey RKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
                    if (RKey==null) {
                        RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    }
                    RKey.SetValue("UbiGamesBackupTool","\""+startuppath+ "\" " +"-b");
                }
                catch (Exception ex) {
                    ex.ToString();
                }
            }
            else if(checkBox.IsChecked == false)
            {
                try
                {
                    RegistryKey RKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
                    if (RKey == null)
                    {
                        RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    }
                    RKey.DeleteValue("UbiGamesBackupTool");
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }
        }

        private void BackupSetting_Click(object sender, RoutedEventArgs e)
        {
            zSetting.Children.Clear();
            WrapPanel rootElement;
            Assembly asmbly = Assembly.GetExecutingAssembly();

            using (Stream stream = asmbly.GetManifestResourceStream("UbiGamesBackupTool.CouldBackup.xaml"))
            {
                rootElement = (WrapPanel)XamlReader.Load(stream);
            }
            zSetting.Children.Add(rootElement);
        }

        public void ALLClick() {
            foreach (WrapPanel e in GameListView.Children) {
                System.Windows.Controls.Button button = e.Children[0] as System.Windows.Controls.Button;
                GamePanelClicked(button, new EventArgs());
            }
        }

        private void ALLPanelSelect_Click(object sender, RoutedEventArgs e)
        {
            ALLClick();
        }
    }
}
